package com.ljr.v1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 设计框架要考虑性能、扩展性、容错性、易用性、通用性
 * @description: 最小原型实现接口性能统计
 * @author: lijunrong
 * @create: 2022/1/18 11:19 AM
 */
public class Metrics {

    private Map<String, List<Long>> responseTimes = new HashMap<>();
    private Map<String, List<Long>> timestamps = new HashMap<>();
    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    public void recordResponseTime(String apiKey, Long responseTime){
        List<Long> responseTimeList = responseTimes.computeIfAbsent(apiKey, t -> new ArrayList<Long>());
        responseTimeList.add(responseTime);
    }

    public void recordTimestamps(String apiKey, Long timestamp){
        List<Long> timestampsList = timestamps.computeIfAbsent(apiKey, t -> new ArrayList<Long>());
        timestampsList.add(timestamp);
    }

    public void startRepeatedReport(long period, TimeUnit timeUnit){
        executor.scheduleAtFixedRate(()->{
            Map<String, Aggregator> aggregatorMap = new HashMap<>();
            responseTimes.forEach((k, v) ->{
                 Aggregator aggregator = aggregatorMap.computeIfAbsent(k, t-> new Aggregator());
                 aggregator.max(v);
                 aggregator.avg(v);
            });

            timestamps.forEach((k, v) ->{
                Aggregator aggregator = aggregatorMap.computeIfAbsent(k, t-> new Aggregator());
                aggregator.count(v);
            });

        }, 0, period, timeUnit);

    }


}
